<template>
  <t-card :bordered="false">
    <!-- 自定义表格 -->
    <custom-table ref="customTableRef" row-key="id" :columns="columns" :api="processDefinitionCRUD.page"
      column-controller-key="SystemJobLogList">
      <template #name="{ row }">
        <t-link  theme="primary" @click="handleBpmnDetail(row)">
          {{ row.name }}
        </t-link>
      
      </template>
      <template #formType="{ row }">
        <t-link v-if="row.formType === 10" theme="primary" @click="handleFormDetail(row)">
          {{ row.formName }}
        </t-link>
        <t-link v-else-if="row.formType === 20" theme="primary" @click="handleFormDetail(row)">
          {{ row.formCustomCreatePath }}
        </t-link>
        <span v-else>暂无表单</span>
      </template>
      <template #suspensionState="{ row }">
        <t-tag theme="success" variant="light" v-if="row.suspensionState === 1">激活</t-tag>
        <t-tag theme="warning" variant="light" v-if="row.suspensionState === 2">挂起</t-tag>
      </template>
      <template #version="{ row }">
        <t-tag v-if="row.version">v{{ row.version }}</t-tag>
        <t-tag theme="warning" v-else>未部署</t-tag>
      </template>
      <template #deploymentTime="{ row }">
        {{ dayjs(row.deploymentTime).format('YYYY-MM-DD HH:mm:ss')}}
      </template>
    </custom-table>

    <!-- 弹窗：表单详情 -->
    <t-dialog header="表单详情" v-model:visible="formDetailVisible" width="800">
      <div v-if="formDetailPreview.rule ">
        <form-create
          v-model="formDetailPreview.formData"
          :rule="formDetailPreview.rule"
          :option="formDetailPreview.option"
        />
      </div>
      <div v-else>暂无表单数据</div>
    </t-dialog>
        <!-- 弹窗：流程模型图的预览 -->
    <t-dialog header="流程图" v-model:visible="bpmnDetailVisible" width="800">
      <MyProcessViewer
        key="designer"
        v-model="bpmnXml"
        :value="bpmnXml as any"
        v-bind="bpmnControlForm"
        :prefix="bpmnControlForm.prefix"
      />
    </t-dialog>
  </t-card>
</template>
<script lang="ts">
export default {
  name: 'ApproveProcessDefinition',
};
</script>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { DialogPlugin, MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import FormCreate from '@/components/FormCreate/index.vue';
import { processDefinitionCRUD } from '@/api/bpm/definition';
import { formCRUD, getFormSimpleList } from '@/api/bpm/form';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import { MyProcessViewer } from '@/components/bpmnProcessDesigner/package'
import { useDictionaryStore } from '@/store';

// 字典仓库
const dictionaryStore = useDictionaryStore();
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// 路由
const route = useRoute();

// columns
const columns: TableCol[] = [
  { colKey: 'id', title: '定义编号' },
  { colKey: 'name', title: '流程名称' },
  { colKey: 'categoryName', title: '定义分类' },
  { colKey: 'formType', title: '表单信息' },
  { colKey: 'version', title: '流程版本' },
  { colKey: 'suspensionState', title: '状态' },
  { colKey: 'deploymentTime', title: '部署时间' },
  { colKey: 'description', title: '定义描述', width: 120 },
];

// 处理初始化表格
const handleInitTable = () => {
  const params = { 
    // pageNo: 1,
    // pageSize: 10, 
    key: route.query.key };
  customTableRef.value.initTable(params);
};

// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
interface FormField {
  field: string;
  title: string;
  type: string;
  value?: any;
  props?: {
    placeholder?: string;
    options?: Array<{ label: string; value: any }>;
  };
  validate?: any[];
}
// 表单详情
const formDetailVisible = ref(false);
const formDetailPreview = ref<{
  rule: FormField[];
  formData: Record<string, any>;
  option: Record<string, any>;
}>({
  rule: [],
  formData: {},
  option: {
    submitBtn: false,
    form: {
      disabled: true
    }
  },
});

const router = useRouter();
// 处理表单详情
const handleFormDetail = async (row: Record<string, any>) => {
  if (row.formType === 10) {
    try {
      // 设置表单
      const data = await formCRUD.get({ id: row.formId });
      
      // 解析字段配置
      let fields: FormField[] = [];
      let conf = {};
      
      try {
        // 解析配置
        conf = JSON.parse(data.conf || '{}');
        
        // 解析字段 - 注意：fields 是字符串数组，每个元素都是 JSON 字符串
        fields = data.fields.map((fieldStr: string) => {
          try {
            const field = JSON.parse(fieldStr);
            return {
              field: field.field || '',
              title: field.title || '',
              type: field.type || 'input',
              value: field.value,
              props: {
                placeholder: `请输入${field.title || ''}`,
                ...field.props,
                // 添加必填验证
                required: field.$required
              },
              validate: field.$required ? [{ required: true, message: `${field.title}必填` }] : undefined
            };
          } catch (fieldError) {
            console.error('解析字段配置失败:', fieldError);
            return null;
          }
        }).filter(Boolean) as FormField[];
      } catch (parseError) {
        console.error('解析表单配置失败:', parseError);
        fields = [];
        conf = {};
      }

      // 更新表单预览数据
      formDetailPreview.value = {
        rule: fields,
        formData: {},
        option: {
          ...conf,
          form: {
            ...(conf as any).form,
            disabled: true
          }
        }
      };

      // 弹窗打开
      formDetailVisible.value = true;
    } catch (error) {
      console.error('获取表单数据失败:', error);
      MessagePlugin.error('获取表单数据失败');
    }
  } else {
    await router.push({
      path: row.formCustomCreatePath
    });
  }
};
/** 流程图的详情按钮操作 */
const bpmnDetailVisible = ref(false)
const bpmnXml = ref(null)
const bpmnControlForm = ref({
  prefix: 'flowable'
})
const handleBpmnDetail = async (row:any) => {
  bpmnXml.value = (await processDefinitionCRUD.get({id:row.id}))?.bpmnXml
  bpmnDetailVisible.value = true
}
onMounted(() => {
  handleInitTable();
});

</script>